from operator import truediv

from fastapi import APIRouter, Depends, HTTPException , Query
from sqlalchemy.orm import Session
from crud import user as crud_user
from schemas import user as schema_user
from schemas import match as schema_match
from utils.database import SessionLocal
from crud import match as crud_match
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from typing import Annotated
from fastapi import Response
from fastapi.responses import JSONResponse
from fastapi.responses import FileResponse
# 新增导入
from models.match import Match
from utils.security import verify_password, create_access_token ,revoke_old_tokens ,validate_token
from utils.strategy import Strategy
from typing import List
from datetime import datetime


def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


def fetch_all_matches(db: Session) -> List:
    page = 1
    limit = 100  # 或者从配置中读取
    all_matches = []

    while True:
        skip = (page - 1) * limit
        matchs = crud_match.get_multi(db, skip=skip, limit=limit)

        if not matchs:
            break  # 没有更多数据，退出循环

        # 处理当前页的匹配数据
        for match in matchs:
            bs = Strategy.get_bs(match.weight)
            match.weight = bs

        all_matches.extend(matchs)
        page += 1  # 进入下一页

    return all_matches

from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session

router = APIRouter()


async def fetch_all_handler(db: Session = Depends(get_db)):
    all_matches = fetch_all_matches(db)
    return all_matches
def filter_league(league_name):
    list = ['USA Major League Soccer','Japan J.League 2','Japan J.League','South Korea K-League 1'
        ,'South Korea K-League 2','Turkey Super Lig','USA Major League Soccer','Argentina Liga Profesional'
        ,'Brazil Serie A','Chile Primera Division','Mexico Liga MX','Australia A-League','Austria Bundesliga-Playoff'
        ,'Copa Libertadores','Russia Premier League'
        ,'CONCACAF Champions Cup']
    if league_name in list:
        return False
    else:
        return True
def filter_time(timestamp):
    """
    判断13位时间戳是否处于当天22点至次日6点之间（包含22点，不包含6点）。

    参数:
        timestamp (int): 13位时间戳（毫秒级）

    返回:
        bool: 处于该时间段返回True，否则False
    """
    # 转换为秒级时间戳
    t_seconds = timestamp // 1000

    # 获取UTC时间的日期零点时间戳
    base = datetime.utcfromtimestamp(t_seconds).replace(
        hour=0, minute=0, second=0, microsecond=0
    ).timestamp()

    # 计算时间段边界
    start = base + 22 * 3600  # 22:00:00
    end = base + 30 * 3600  # 次日6:00:00（24+6小时）

    return start <= t_seconds <= end

def filter_pankou(prediction):
    list = ['Over 2.5','Over 2.75']
    if prediction in list:
        return True
    else:
        return False

def test1():
    db = SessionLocal()
    matchs = db.query(Match).all()
    print(len(matchs))
    matchs_im = []
    money = 0
    for match in matchs:

        if filter_league(match.league):
            matchs_im.append(match)
    print(len(matchs_im))

    money = 0
    for match in matchs_im:
        print(match.league)
        if match.performance == 'Win':
            money += 1
            # money+=2120
        if match.performance == 'Lose':
            money -= 1
            # money -= 2120
    print(money)
def test2():
    db = SessionLocal()
    matchs = db.query(Match).all()
    print(len(matchs))
    matchs_im = []
    money = 0
    for match in matchs:

        if filter_pankou(match.prediction):
            matchs_im.append(match)
    print(len(matchs_im))

    money = 0
    for match in matchs_im:
        print(match.league)
        if match.performance == 'Win':
            money += 1
        if match.performance == 'Lose':
            money -= 1
        if match.performance == 'Win Half':
            money += 0.5
        if match.performance == 'Lose Half':
            money -= 0.5
        print(money)

def test3():
    db = SessionLocal()
    matchs = db.query(Match).all()
    print(len(matchs))
    matchs_im = []
    money = 0
    for match in matchs:

        if filter_time(match.start_time):
            matchs_im.append(match)
    print(len(matchs_im))

    money = 0
    for match in matchs_im:
        print(match.league)
        if match.performance == 'Win':
            money += 1
        if match.performance == 'Lose':
            money -= 1
        if match.performance == 'Win Half':
            money += 0.5
        if match.performance == 'Lose Half':
            money -= 0.5
        print(money)

if __name__ == "__main__":
    test2()